package kr.co.bettersoft.waitnumberstorem.fragment;

import java.util.List;

import kr.co.bettersoft.waitnumberstorem.activity.LoginActivity;
import kr.co.bettersoft.waitnumberstorem.activity.R;
import kr.co.bettersoft.waitnumberstorem.common.CommonConstant;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
 * 탭 액티비티 대신 프래그먼트 방식을 사용.
 *  탭 액티비티의 기능을 제공
 *  하단 대기 등록 / 대기현황/ 추천 / 더보기 등의 메뉴를 등록하여 터치하여 해당 화면으로 이동 
 * @author blue
 *
 */
public class FragmentHome extends FragmentActivity{
	static String TAG = "FragmentHome";
	
	public static Activity fragmentHome ;
	
	// 공용 프립스
	SharedPreferences sharedPrefCustom;		
	
	// 자동 로그인 및 하드웨어 홈버튼 동작 관련
	static String merchantId;			// 가맹점 아이디
	public static Boolean autoLogin ;		

	// 로케일
	static String countryCode;
	static String languageCode;
	
	Button registerWaitBtn;
	Button waitUserListBtn;
	Button memberStoreReviewListBtn;
	Button settingsBtn;
	
	int nowMenuPostion = 0;	// 같은 화면 두번 호출방지
	Boolean isSame = false;
	
	public static int restCallCnt = 0; 
	
	// 뒤로가기 버튼으로 닫을때 2번만에 닫히도록
	static int app_end = 0;			
	
	int registerWaitFragmentId;		// 뒤로가기 버튼에 대한 상호 작용을 위해 첫번째 fragment 의 아이디값을 저장.
////////////////////////////////////////////////////////////////////////////////////////////////////
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.fragment_main);
		
		checkNetworkContinue();
		
		fragmentHome = FragmentHome.this;
		
		sharedPrefCustom = getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		autoLogin = sharedPrefCustom.getBoolean("autoLoginChecked", false);
		
		registerWaitBtn = (Button) findViewById(R.id.register_wait_btn);
		waitUserListBtn = (Button) findViewById(R.id.wait_user_list_btn);
		memberStoreReviewListBtn = (Button) findViewById(R.id.member_store_review_list_btn);
		settingsBtn = (Button) findViewById(R.id.settings_btn);
		
		registerWaitBtn.setOnClickListener(onBtnClickListener);
		waitUserListBtn.setOnClickListener(onBtnClickListener);
		memberStoreReviewListBtn.setOnClickListener(onBtnClickListener);
		settingsBtn.setOnClickListener(onBtnClickListener);
		
		showDetailFragment("RegisterWait");
	}
	
	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	private void showDetailFragment(String $tag)
	{
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment newFragment = new RegisterWaitFragment();
		
		if ($tag.contains("RegisterWait")) {
			if(nowMenuPostion!=1){
				nowMenuPostion = 1;
				registerWaitBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_5_over));
				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_6));
				memberStoreReviewListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_7));
				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_8));
				newFragment = new RegisterWaitFragment();		
				isSame = false;
			}else{
				isSame = true;
			}
		}else if($tag.contains("WaitUserList")){
			if(nowMenuPostion!=2){
				nowMenuPostion = 2;
				registerWaitBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_5));
				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_6_over));
				memberStoreReviewListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_7));
				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_8));
				newFragment = new WaitUserListFragment();			
				isSame = false;
			}else{
				isSame = true;
			}
			
			
		}else if($tag.contains("ReviewList")){
			if(nowMenuPostion!=3){
				nowMenuPostion = 3;
				registerWaitBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_5));
				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_6));
				memberStoreReviewListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_7_over));
				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_8));
				newFragment = new ReviewListFragment();			
				isSame = false;
			}else{
				isSame = true;
			}
		}else if($tag.contains("Settings")){
			if(nowMenuPostion!=4){
				nowMenuPostion = 4;
				registerWaitBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_5));
				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_6));
				memberStoreReviewListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_7));
				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_8_over));
				newFragment = new SettingsFragment();			
				isSame = false;
			}else{
				isSame = true;
			}
		}
		
		if(!isSame){
			ft.replace(R.id.details, newFragment);								// fragment_main 의 detail 자리에 넣음
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			ft.commit();
			if(nowMenuPostion == 1){
				Log.d(TAG,"newFragment::"+newFragment.getId());
				registerWaitFragmentId = newFragment.getId();
			}
		}
	}
	
	private OnClickListener onBtnClickListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			showDetailFragment(v.getTag().toString());
		}
	};
	
	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	public static Boolean restCallCntUp(){
		Boolean cntResult = false;
		restCallCnt = restCallCnt +1;
		Log.d(TAG,"restCallCnt:"+restCallCnt);
		if(restCallCnt==1){
			cntResult = true;
		}else{
			restCallCnt = restCallCnt -1;
			cntResult = false;
		}
		return cntResult;
	}
	public static Boolean restCallCntDown(){
		Boolean cntResult = false;
		restCallCnt = restCallCnt -1;
		Log.d(TAG,"restCallCnt:"+restCallCnt);
		if(restCallCnt==0){
			cntResult = true;
		}else{
			cntResult = false;
		}
		return cntResult;
	}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	
	// 통신 체크.
	public void checkNetworkContinue(){
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
						NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
						if(ni!=null){
							boolean isWifiAvail = ni.isAvailable();
							boolean isWifiConn = ni.isConnected();
							ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
							boolean isMobileAvail = ni.isAvailable();
							boolean isMobileConn = ni.isConnected();
							String status = "WiFi Avail = " + isWifiAvail + "// WiFi Conn = "
							+ isWifiConn + "// Mobile // Avail = " + isMobileAvail
							+ "// Conn = " + isMobileConn;
//							Log.d(TAG,"status:"+status);
							Thread.sleep(5000);
							checkNetworkContinue();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
	}
	
	
	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 유틸	

		/**
		 * isForeGround
		 *  프로세스가 최상위로 실행중인지 검사한다
		 *
		 * @param
		 * @param
		 * @return rtn    @return true = 최상위
		 */
		public Boolean isForeGround(){
			ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE );
			List<RunningTaskInfo> list = am.getRunningTasks(1);
			ComponentName cn = list.get(0). topActivity;
			String name = cn.getPackageName();
			Boolean rtn = false;
			if(name.indexOf(getPackageName()) > -1){
				rtn = true;
			} else{
				rtn = false;
			}
			return rtn;
		}
	
	/*
	 *  닫기 버튼 2번 누르면 종료 됨.(non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	/**
	 * onBackPressed
	 *   닫기 버튼 2번 누르면 종료 한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	@Override
	public void onBackPressed() {
		Log.d(TAG, "FragmentHome finish");	
		
		// 대기 등록 프래그먼트 인지 확인.
		if(nowMenuPostion==1){
			Log.d(TAG,"register wait fragment");
			RegisterWaitFragment registerWaitFragment = (RegisterWaitFragment)getSupportFragmentManager().findFragmentById(registerWaitFragmentId);
			if(registerWaitFragment.checkFinishYn()){	
				Log.d(TAG,"mode : 1");
				finishAtTwo();
				// 대기 등록중인 화면. 
			}else{
				// 안해도 됨
				Log.d(TAG,"mode != 1. init screen");
			}
			// 일반 화면
		}else{
			Log.d(TAG,"other fragment");
			finishAtTwo();
		}
	}

	/*
	 * 3초 이내에 두번 연속 호출되면 어플을 종료함.
	 */
	public void finishAtTwo(){
		if(app_end == 1){
			Log.d(TAG,"kill all");
			finish();
		}else{
			app_end = 1;
			Toast.makeText(FragmentHome.this, R.string.noti_back_finish, Toast.LENGTH_SHORT).show();
			new Thread( 
					new Runnable(){
						public void run(){
							try {
								Thread.sleep(3000);
								app_end = 0;
							} catch (InterruptedException e) {e.printStackTrace();}
						}
					}
			).start();
		}
	}
	
	
	/**
	 * onResume
	 * 액티비티 리쥼시 바탕화면 갔다왔는지 확인해서 로그인창을 띄운다
	 *
	 * @param
	 * @param
	 * @return 
	 */
	@Override
	protected void onResume() {
		super.onResume();
		if(CommonConstant.comeBack){		// 바탕화면 갔다온 경우 - 로그인 액티비티 실행. 그냥죽을지/정상로그인할지/로그인하고죽을지
			Intent LoginIntent = new Intent(FragmentHome.this, LoginActivity.class);
			startActivity(LoginIntent);
		}
	}
	
	/**
	 * onPause
	 * 종료인지, 홈버튼으로 나간건지 확인하여 처리한다
	 *
	 * @param
	 * @param
	 * @return 
	 */
	@Override
	protected void onPause() {
		super.onPause();
		if(!isForeGround()){  
			if(!autoLogin){				// 자동 로그인 아닐 경우에만 로그인 창이 뜬다.
				CommonConstant.comeBack = true;				// 다시 돌아왔을때 알아볼수 있도록 함.
				CommonConstant.tempMyID = merchantId;				// 다시 돌아왔을때 알아볼수 있도록 함.
			}
		}
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		System.exit(0);
	}
}
